var $bgmAudio = $("#bgmAudio");
var bgmAudio = $bgmAudio[0];
var bgmBtn = document.getElementById('bgmBtn');
var isPlay = true;
var musicData = null;
if (!localStorage.getItem('token')) {
	// 请求注册接口
	$.ajax({
		type: "POST",
		contentType: "application/json;charset=UTF-8",
		url: PATHAPI + "/register",
		success: function(result) {
			console.log(result)
			if (result.status == 'success') {
				localStorage.setItem('token', result.data.token);
				getMusicData();
			} else {
				alert(result.message);
			}
		}
	})
} else {
	musicData = sessionStorage.getItem("musicData");
	if (!musicData) {
		getMusicData();
	} else {
		musicData = JSON.parse(musicData);
		// 设置音乐参数
		setMusicData();
	}
}
// 设置音乐参数
function setMusicData() {
	$("#bgmAudio").attr("src", musicData.video_file); // 音乐链接
	$("#bgmBtn").css({
		backgroundImage: "url(" + musicData.play_img + ")"
	})
}
// 请求音乐数据
function getMusicData() {
	$.ajax({
		type: "GET",
		headers: {
			Token: localStorage.getItem('token')
		},
		contentType: "application/json;charset=UTF-8",
		url: PATHAPI + "/index.php/text?page_no=music",
		success: function(res) {
			let music = res.data || {};
			music.video_file = music.video_file || {};
			music.pause_img = music.pause_img || {};
			music.play_img = music.play_img || {};
			music.pause_img = music.pause_img.file_url || "/static/music/music_btn_stop.png";
			music.play_img = music.play_img.file_url || "/static/music/music_btn.png";
			music.video_file = music.video_file.file_url || "/static/music/bgm.mp3";
			musicData = music;
			sessionStorage.setItem("musicData", JSON.stringify(musicData));
			// 设置音乐参数
			setMusicData();
		}
	})
}
// 暂停/播放切换
function bgmBtnClick() {
	console.log(isPlay)
	if (isPlay) {
		// 暂停
		bgmBtn.classList.add("suspended");
		bgmAudio.pause();
		$("#bgmBtn").css({
			backgroundImage: "url(" + musicData.pause_img + ")"
		})
		isPlay = false;
	} else {
		// 播放
		bgmBtn.classList.remove("suspended");
		bgmAudio.play();
		$("#bgmBtn").css({
			backgroundImage: "url(" + musicData.play_img + ")"
		})
		isPlay = true;
	}
}
// 自动播放
function audioAutoPlay() {
	var play = function() {
		bgmAudio.play();
		document.removeEventListener("touchstart", play, false);
	};
	bgmAudio.play();
	document.addEventListener("WeixinJSBridgeReady", function() {
		console.log(play)
		play();
	}, false);
	document.addEventListener("touchstart", play, false);
}
document.addEventListener('DOMContentLoaded', function() {
	audioAutoPlay();
});
// 监听返回事件？跳转外部链接后返回，音频事件失效
window.addEventListener("popstate", function(e) {

}, false);
